const Emitter = require('events');
const { v4: uuidv4 } = require('uuid');

class TtsWorkerSession extends Emitter {
  constructor(ttsWorker, sessionId) {
    super();
    this.ttsWorker = ttsWorker;
    this.sessionId = sessionId;//uuidv4();
  }
  // 发送给tts 后端 python
  sendJson(message) {
    const json = JSON.parse(message);
    if(json.session_id === this.sessionId) {
      this.ttsWorker.send(JSON.stringify(json));
      console.log("Send meesage to TTS Worker:", json);
    }else {
      console.log("TTS sensionID error");
    }
  }

  finish() {
    this.sendJson(JSON.stringify({ type: 'finish', timeStamp: Date.now(), session_id: this.sessionId}));
    this.ttsWorker.removeSession(this.sessionId);
  }

}

class TtsWorker extends Emitter {
  constructor(ws, workerId) {
    super();
    this.sessions = new Map();
    this.workerId = workerId;
    this.ws = ws;
    this.initWebSocket();
  }

  initWebSocket() {
    this.ws.on('message', this.onMessage.bind(this));
    this.ws.on('close', this.onClose.bind(this));
    this.ws.on('error', this.onError.bind(this));
  }

  send(data) {
    this.ws.send(data);
  }

  onMessage(message, isBinary) {
    try {
      if (isBinary) {
        console.log("Recv tts work audio binary data:", message.byteLength);
        //const data = decoder.decode(message);
        //this.sessions.get(session_id).emit('audio', message);
      } else {
        const json = JSON.parse(message);
        json.timeStamp = Date.now();
        const { type, text, session_id} = json;
        if (type === 'tts') {
          //console.log("Recv tts work message data:", json);
          this.sessions.get(session_id).emit('tts', JSON.stringify(json));
        } else if(type === 'audio') {
          let audioBuffer = Buffer.from(text, 'base64');
          this.sessions.get(session_id).emit('audio', audioBuffer);
        } else {
          console.error('收到未知消息类型:', json.type);
        }
      }
    } catch (error) {
      console.error('解析消息时出错:', error);
    }
  }

  onClose() {
    this.emit('close');
  }

  onError(error) {
    console.error(`工作节点 ${this.workerId} 发生错误:`, error);
    this.emit('error', error);
  }

  newSession(sessionId) {
    const session = new TtsWorkerSession(this, sessionId);
    this.sessions.set(session.sessionId, session);
    return session;
  }

  removeSession(sessionId) {
    this.sessions.delete(sessionId);
  }

  close() {
    this.sessions.forEach(session => session.emit('close'));
    this.sessions.clear();
    this.ws.close();
  }
}

module.exports = TtsWorker;
